import React from 'react';
import styles from './Message.css';
import { WhiteSpace, WingBlank, Flex, Button } from 'antd-mobile';
import avatar from '../../framework/utils/avatar';

const Message = ({ message, onViewMember = () => {}, actionElements }) => {
  const handledStatus = 2;
  const renderHandleButton = (message) => {
    if (message.actionRequired === 1 && message.status !== handledStatus) {
      return (
        <div>
          <WhiteSpace size="lg" />
          {actionElements}
        </div>
      )
    }
  }

  const renderSenderMessage = (message) => {
    const senderExt = message.senderExt ? JSON.parse(message.senderExt) : {};
    return (
      <div key={message.id}>
        <div className={styles.time}>{message.createTime}</div>
        <div className={styles.contentWrapper}>
          <div className={styles.avatar} onClick={() => onViewMember(senderExt.id)}>{avatar(senderExt.name, senderExt.avatar)}</div>
          <div className={styles.informalText}>
            <div>{message.content}</div>
            {renderHandleButton(message)}
          </div>
        </div>
      </div>
    )
  }

  const renderReceiverMessage = (message) => {
    const receiverExt = message.receiverExt ? JSON.parse(message.receiverExt) : {};
    return (
      <div key={message.id}>
        <div className={styles.time}>{message.createTime}</div>
        <div className={styles.contentWrapper}>
          <div className={styles.informalText}>{message.content}</div>
          <div className={styles.avatar} onClick={() => onViewMember(receiverExt.id)}>{avatar(receiverExt.name, receiverExt.avatar)}</div>
        </div>
      </div>
    )
  }

  const renderReplyMessages = (currentUserId, messages) => {
    if (messages) {
      return messages.map(message => {
        if (currentUserId === message.senderId) {
          return renderReceiverMessage(message);
        }
        return renderSenderMessage(message);
      })
    }
  }

  const senderExt = message.senderExt ? JSON.parse(message.senderExt) : {};
  const receiverExt = message.receiverExt ? JSON.parse(message.receiverExt) : {};

  return (
    <div className={styles.normal}>
      {renderSenderMessage(message)}
      {renderReplyMessages(message.receiverId, message.replyMessages)}
    </div>
  )
}

export default Message;
